package com.baayso.demo.sj.common.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.alibaba.fastjson.JSON;
import com.baayso.demo.sj.utils.OperationResult;
import com.baayso.demo.sj.utils.WebUtils;

/**
 * 异常处理器，返回 json数据。
 * 
 * @author ChenFangjie
 * 
 * @since 1.0.0
 * 
 * @version 1.0.0
 *
 */
public class JsonSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {

    // private static final Logger logger = LoggerFactory.getLogger(JsonSimpleMappingExceptionResolver.class);

    // private JsonMapper jsonMapper = new JsonMapper();

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;

        OperationResult result = new OperationResult(false);
        result.setMessage(ex.getMessage());

        String body = JSON.toJSONString(result);
        // String body = this.jsonMapper.toJson(result);

        WebUtils.writeJson(response, body, httpStatus.value());

        return new ModelAndView();
    }

}
